package com.lucker.service.wx;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.lucker.common.util.HttpUtil;
import com.lucker.common.util.SysRestrictionsConfigType;
import com.lucker.common.util.WeChatSession;
import com.lucker.ds.model.SysRestrictionsConfig;
import com.lucker.framework.exception.BaseServiceException;
import com.lucker.service.sys.SysRestrictionsConfigService;

@Service
public class WxServiceImpl implements WxService {
	
	@Autowired
	SysRestrictionsConfigService sysRestrictionsConfigService;
	
	private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
	
	public Logger getLOGGER() {
		return LOGGER;
	}
	
	public WeChatSession requestWxSession(String code) {
		
		SysRestrictionsConfig wxConfig_appid = sysRestrictionsConfigService.getSysRestrictionsConfig(SysRestrictionsConfigType.WX_APPID);
		if(wxConfig_appid == null || StringUtils.isBlank(wxConfig_appid.getName())) {
			throw new BaseServiceException("配置表中未配置 wx appid");
		}
		SysRestrictionsConfig wxConfig_secret = sysRestrictionsConfigService.getSysRestrictionsConfig(SysRestrictionsConfigType.WX_SECRET);
		if(wxConfig_secret == null || StringUtils.isBlank(wxConfig_secret.getName())) {
			throw new BaseServiceException("配置表中未配置 wx secret");
		}
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig_appid.getName() + "&secret=" + wxConfig_secret.getName() + "&js_code=" + code + "&grant_type=authorization_code";
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			String wx_resp = HttpUtil.post(url, params);
			WeChatSession weSession = JSONObject.parseObject(wx_resp, WeChatSession.class);
			return weSession;
		}catch (Exception e) {
			getLOGGER().error("请求微信发生错误 : {} ", e);
			throw new BaseServiceException("请求微信发生错误,请重试");
		}
		
		
	}
	
}
